package com.hutianao.gqgl.spring.security;


import com.hutianao.gqgl.user.entity.SecurityUser;
import com.hutianao.gqgl.mybatis.entity.PtUserEntity;
import com.hutianao.gqgl.user.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("userDetailsService")
public class GdmtUserDetailsService implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //用户名鉴权
        PtUserEntity ptUserEntity =  userService.queryIsSumUserInfoByName(username);
        if(ptUserEntity == null){
            ptUserEntity =  userService.queryUserInfoByMail(username);
            ptUserEntity.setPassword("email");
            if(ptUserEntity == null){
                throw  new IllegalArgumentException(username + " is not exit.");
            }
        }
        //权限管理
//26b10a1b66f1408088097a1c621d151e
        List<String> authStrList = userService.queryrivilegeList(ptUserEntity.getUserUuid());
//        String password = passwordEncoder.encode("123456");
        List<GrantedAuthority> collection = new ArrayList<>();
        for(String authString : authStrList ){
            if(authString != null){
                collection.add(new SimpleGrantedAuthority("ROLE_" + authString));
            }
        }
//        collection.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
//        collection.add(new SimpleGrantedAuthority("ROLE_USER_UPDATE"));
//        collection.add(new SimpleGrantedAuthority("ROLE_TEST1"));
//        collection.add(new SimpleGrantedAuthority("ROLE_TEST1_ADD"));
        // 参数分别是：用户名，密码，用户权限
        SecurityUser user =new  SecurityUser(ptUserEntity.getUserName(), ptUserEntity.getPassword(), ptUserEntity,collection);


        return user;
    }
}

